<template>
	<div class="subject-analyze">
		<el-card class="analyze-card">
			<template #header>
				<div class="card-header">
					<div class="filter-section">
						<el-select v-model="selectedYear" placeholder="学年" class="filter-item">
							<el-option v-for="year in academicYears" :key="year" :label="year" :value="year" />
						</el-select>
						<el-select
							v-model="selectedClass"
							placeholder="班级"
							class="filter-item"
							style="width: 50vh"
						>
							<el-option
								v-for="item in classList"
								:key="item.id"
								:label="item.className"
								:value="item.id"
							/>
						</el-select>
						<el-button type="primary" @click="handleQuery" :loading="loading" class="query-btn">
							查询
						</el-button>
						<div class="right-filters">
							<el-select
								v-model="selectedSubject"
								placeholder="科目"
								class="filter-item"
								style="width: 150px; margin-right: 10px"
								@change="handleSubjectChange"
							>
								<el-option
									v-for="item in subjectList"
									:key="item.id"
									:label="item.subjectName"
									:value="item.id"
								/>
							</el-select>
							<el-select
								v-model="selectedScoreType"
								placeholder="考试类型"
								style="width: 100px"
								@change="handleScoreTypeChange"
							>
								<el-option label="理论" value="theory" />
								<el-option label="实践" value="practice" />
							</el-select>
						</div>
					</div>
				</div>
			</template>

			<div class="charts-container">
				<div v-if="!hasChartData" class="empty-chart-tip">
					<el-empty description="尚未查询数据" :image-size="200">
						<!-- <template #description>
							<p>请选择筛选条件后点击查询按钮</p>
						</template>
						<el-button type="primary" @click="handleQuery" :disabled="!canQuery">查询</el-button> -->
					</el-empty>
				</div>
				<template v-else>
					<el-row :gutter="20">
						<el-col :span="12">
							<div ref="scoreDistributionRef" class="chart-item"></div>
						</el-col>
						<el-col :span="12">
							<div ref="scorePercentageRef" class="chart-item"></div>
						</el-col>
					</el-row>

					<el-row :gutter="20" class="statistics-row">
						<el-col :span="6" v-for="stat in statistics" :key="stat.label">
							<el-card class="stat-card" shadow="hover">
								<div class="stat-value">{{ stat.value }}</div>
								<div class="stat-label">{{ stat.label }}</div>
							</el-card>
						</el-col>
					</el-row>

					<!-- 考试情况信息 -->
					<el-row :gutter="20" class="statistics-row">
						<!-- 根据当前选择的考试类型显示对应的考试情况 -->
						<template v-if="selectedScoreType === 'theory'">
							<el-col :span="6">
								<el-card class="stat-card" shadow="hover">
									<div class="stat-value">{{ theoryViolations }}</div>
									<div class="stat-label">违规人数</div>
								</el-card>
							</el-col>
							<el-col :span="6">
								<el-card class="stat-card" shadow="hover">
									<div class="stat-value">{{ theoryAbsences }}</div>
									<div class="stat-label">缺考人数</div>
								</el-card>
							</el-col>
							<el-col :span="6" v-if="theoryViolationStudents.length > 0">
								<el-card class="student-card" shadow="hover">
									<div class="student-info">
										<div class="student-label">违规学生</div>
										<div class="student-list">
											<el-tag
												v-for="student in theoryViolationStudents"
												:key="student.id"
												class="student-tag"
												type="danger"
												@click="showStudentDetail(student.id)"
											>
												{{ student.name }}
											</el-tag>
										</div>
									</div>
								</el-card>
							</el-col>
							<el-col :span="6" v-if="theoryTopStudents.length > 0">
								<el-card class="student-card" shadow="hover">
									<div class="student-info">
										<div class="student-label">最高分学生</div>
										<div class="student-list">
											<el-tag
												v-for="student in theoryTopStudents"
												:key="student.id"
												class="student-tag"
												type="success"
												@click="showStudentDetail(student.id)"
											>
												{{ student.name }}
											</el-tag>
										</div>
									</div>
								</el-card>
							</el-col>
						</template>
						<template v-else>
							<el-col :span="6">
								<el-card class="stat-card" shadow="hover">
									<div class="stat-value">{{ practiceViolations }}</div>
									<div class="stat-label">违规人数</div>
								</el-card>
							</el-col>
							<el-col :span="6">
								<el-card class="stat-card" shadow="hover">
									<div class="stat-value">{{ practiceAbsences }}</div>
									<div class="stat-label">缺考人数</div>
								</el-card>
							</el-col>
							<el-col :span="6" v-if="practiceViolationStudents.length > 0">
								<el-card class="student-card" shadow="hover">
									<div class="student-info">
										<div class="student-label">违规学生</div>
										<div class="student-list">
											<el-tag
												v-for="student in practiceViolationStudents"
												:key="student.id"
												class="student-tag"
												type="danger"
												@click="showStudentDetail(student.id)"
											>
												{{ student.name }}
											</el-tag>
										</div>
									</div>
								</el-card>
							</el-col>
							<el-col :span="6" v-if="practiceTopStudents.length > 0">
								<el-card class="student-card" shadow="hover">
									<div class="student-info">
										<div class="student-label">最高分学生</div>
										<div class="student-list">
											<el-tag
												v-for="student in practiceTopStudents"
												:key="student.id"
												class="student-tag"
												type="success"
												@click="showStudentDetail(student.id)"
											>
												{{ student.name }}
											</el-tag>
										</div>
									</div>
								</el-card>
							</el-col>
						</template>
					</el-row>
				</template>
			</div>
		</el-card>
	</div>
</template>

<script lang="ts" setup name="gradeAnalyze">
import { ref, onMounted, onActivated, onDeactivated, computed, nextTick, watch } from 'vue'
import * as echarts from 'echarts'
import type { EChartsOption } from 'echarts'
import { TScore } from '@/Types/score'
import { getScoreListBySpecificService } from '@/api/education/score'
import { useUserStore } from '@/stores'
import { getSubjectBySpecificService } from '@/api/education/subject'
import { getClassnameByIdService } from '@/api/education/classname'
import { getScoreStatsListService } from '@/api/education/scoreStats'
import { ElLoading, ElMessage } from 'element-plus'
import { getUserByUserInfoService } from '@/api/user'
import { useRouter, useRoute } from 'vue-router'

// 获取用户store
const userStore = useUserStore()
const classIdList = userStore.userInfo.userInfo.classIdList
const router = useRouter()
const route = useRoute()

// 组件挂载时初始化
onMounted(() => {
	// 默认选择理论考试类型
	selectedScoreType.value = 'theory'

	// 始终获取基础数据（班级和科目列表）
	fetchScoreData().then(() => {
		// 如果有查询条件，自动查询
		if (canQuery.value) {
			nextTick(() => {
				handleQuery()
			})
		}
	})

	// 监听窗口大小变化，重新调整图表大小
	window.addEventListener('resize', () => {
		// 只有在有数据的情况下才调整大小
		if (scoreData.value.length > 0) {
			if (scoreDistributionChart) {
				scoreDistributionChart.resize()
			}
			if (scorePercentageChart) {
				scorePercentageChart.resize()
			}
		}
	})
})

const selectedYear = ref('')
const selectedClass = ref<number | undefined>()
const selectedSubject = ref<number | undefined>()
const selectedScoreType = ref('theory')
const scoreData = ref<TScore[]>([])
const allScoreData = ref<TScore[]>([])
const academicYears = ref<string[]>([])
const classList = ref<{ id: number; className: string }[]>([])
const subjectList = ref<{ id: number; subjectName: string }[]>([])
const scoreDistributionRef = ref<HTMLElement>()
const scorePercentageRef = ref<HTMLElement>()
const userId = userStore.userInfo.userInfo.userId
const loading = ref(false)

// 图表数据初始化标志
const chartDataInitialized = ref(false)
// 是否可以查询
const canQuery = computed(() => {
	return selectedYear.value && selectedClass.value
})

// 是否有图表数据
const hasChartData = computed(() => {
	return chartDataInitialized.value
})

// 图表实例
let scoreDistributionChart: echarts.ECharts | null = null
let scorePercentageChart: echarts.ECharts | null = null

// 违规和缺考信息
const theoryViolations = ref(0)
const theoryAbsences = ref(0)
const theoryViolationStudents = ref<{ id: number; name: string }[]>([])
const theoryTopStudents = ref<{ id: number; name: string }[]>([])
const practiceViolations = ref(0)
const practiceAbsences = ref(0)
const practiceViolationStudents = ref<{ id: number; name: string }[]>([])
const practiceTopStudents = ref<{ id: number; name: string }[]>([])

// 统计数据
const statistics = ref([
	{ label: '平均分', value: '0' },
	{ label: '最高分', value: '0' },
	{ label: '最低分', value: '0' },
	{ label: '及格率', value: '0%' }
])

// 处理数据
const processScoreData = (data: TScore[]) => {
	// 存储所有原始数据
	allScoreData.value = data

	// 提取唯一的学年
	const years = [...new Set(data.map((item) => item.academicYear))]
	academicYears.value = years

	// 使用pinia中存储的classIdList获取班级信息
	if (classIdList && classIdList.length > 0) {
		fetchClassInfo(classIdList)
	} else {
		// 兜底处理：如果pinia中没有classIdList，则从成绩数据中提取
		const classIds = [...new Set(data.map((item) => item.classId))]
		fetchClassInfo(classIds)
	}

	// 设置默认选中值
	if (years.length > 0 && !selectedYear.value) {
		selectedYear.value = years[0]
	}
}

// 获取班级信息
const fetchClassInfo = async (classIds: number[]) => {
	try {
		const promises = classIds.map((id) => getClassnameByIdService(id))
		const res = await Promise.all(promises)
		classList.value = res.map((item) => ({
			id: item.data.data.classId,
			className: `${item.data.data.academy}-${item.data.data.major}-${item.data.data.grade}级-${item.data.data.classname}班`
		}))

		// 如果没有选择班级，默认选择第一个
		if (!selectedClass.value && classList.value.length > 0) {
			selectedClass.value = classList.value[0].id
		}
	} catch (error) {
		console.error('获取班级信息失败:', error)
	}
}

// 获取科目信息
const fetchSubjectInfo = async (subjectIds: number[]) => {
	try {
		const res = await getSubjectBySpecificService(subjectIds)
		subjectList.value = res.data.data.map((item: any) => ({
			id: item.id,
			subjectName: item.subject
		}))

		// 如果没有选择科目，默认选择第一个
		if (!selectedSubject.value && subjectList.value.length > 0) {
			selectedSubject.value = subjectList.value[0].id
		}
	} catch (error) {
		console.error('获取科目信息失败:', error)
	}
}

// 获取班级对应的科目列表
const fetchSubjectsByClassAndYear = async () => {
	if (!selectedClass.value || !selectedYear.value) return

	try {
		// 根据选择的班级和学年获取成绩数据
		const res = await getScoreListBySpecificService({
			userId,
			academicYear: selectedYear.value,
			classId: selectedClass.value
		})

		if (res.data.data && res.data.data.length > 0) {
			// 从成绩数据中提取科目ID，确保是number类型
			const subjectIds = [
				...new Set(res.data.data.map((item: TScore) => item.subjectId))
			] as number[]
			// 获取科目信息
			await fetchSubjectInfo(subjectIds)
		} else {
			// 如果没有数据，清空科目列表
			subjectList.value = []
			selectedSubject.value = undefined
		}
	} catch (error) {
		console.error('获取班级对应科目列表失败:', error)
		ElMessage.error('获取科目列表失败')
	}
}

// 添加监听器，当班级或学年变化时获取对应的科目列表
watch(
	[selectedClass, selectedYear],
	() => {
		// 重置科目选择
		selectedSubject.value = undefined
		// 获取新的科目列表
		fetchSubjectsByClassAndYear()
	},
	{ immediate: false }
)

// 获取用户信息
const fetchUserInfo = async (userId: number) => {
	// console.log(userId)
	try {
		const res = await getUserByUserInfoService({ userId })
		// console.log(res.data.data)
		return {
			id: userId,
			name: res.data.data[0].uname || `学生${userId}`
		}
	} catch (error) {
		// console.error('获取用户信息失败:', error)
		ElMessage.error('获取用户信息失败')
	}
}

// 获取统计数据
const fetchStatsData = async () => {
	// 检查是否选择了班级和学年
	if (!selectedYear.value || !selectedClass.value) {
		ElMessage.warning('请选择学年和班级')
		return
	}

	loading.value = true
	const loadingInstance = ElLoading.service({
		target: '.charts-container',
		text: '加载中...'
	})

	try {
		// 基本查询参数
		const baseParams = {
			academicYear: selectedYear.value,
			classId: selectedClass.value
		}

		// 如果选择了科目，则添加到查询参数
		const params = selectedSubject.value
			? { ...baseParams, subjectId: selectedSubject.value }
			: baseParams

		// 获取成绩列表数据（用于成绩分布图和成绩等级占比）
		const scoreListRes = await getScoreListBySpecificService({
			userId,
			...params
		})

		// 获取统计数据（用于违规和缺考信息）
		const statsRes = await getScoreStatsListService(params)

		// 处理成绩列表数据
		if (scoreListRes.data.data && scoreListRes.data.data.length > 0) {
			const filteredScoreData = scoreListRes.data.data
			scoreData.value = filteredScoreData

			// 更新图表
			updateChartsFromScoreData(filteredScoreData)

			// 设置图表数据初始化标志
			chartDataInitialized.value = true
		} else {
			ElMessage.warning('没有找到符合条件的成绩数据')
			// 清空图表
			if (scoreDistributionChart) {
				scoreDistributionChart.clear()
			}
			if (scorePercentageChart) {
				scorePercentageChart.clear()
			}

			// 有查询但无数据，也设置为初始化
			chartDataInitialized.value = true
		}

		// 处理统计数据
		if (statsRes.data.data && statsRes.data.data.length > 0) {
			const data = statsRes.data.data[0]

			// 根据所选考试类型更新统计数据
			if (selectedScoreType.value === 'theory') {
				statistics.value = [
					{ label: '平均分', value: data.avgScoreTheory?.toString() || '0' },
					{ label: '最高分', value: data.maxScoreTheory?.toString() || '0' },
					{ label: '最低分', value: data.minScoreTheory?.toString() || '0' },
					{ label: '及格率', value: `${data.passRateTheory || 0}%` }
				]
			} else {
				statistics.value = [
					{ label: '平均分', value: data.avgScorePractice?.toString() || '0' },
					{ label: '最高分', value: data.maxScorePractice?.toString() || '0' },
					{ label: '最低分', value: data.minScorePractice?.toString() || '0' },
					{ label: '及格率', value: `${data.passRatePractice || 0}%` }
				]
			}

			// 更新违规和缺考信息
			updateViolationInfo(data)
		} else {
			ElMessage.warning('没有找到符合条件的统计数据')
			// 清空统计数据
			statistics.value = [
				{ label: '平均分', value: '0' },
				{ label: '最高分', value: '0' },
				{ label: '最低分', value: '0' },
				{ label: '及格率', value: '0%' }
			]
		}
	} catch (error) {
		console.error('获取数据失败:', error)
		ElMessage.error('获取数据失败，请稍后重试')
	} finally {
		loadingInstance.close()
		loading.value = false
	}
}

// 更新违规和缺考信息
const updateViolationInfo = async (data: any) => {
	// 理论考试信息
	theoryViolations.value = data.theoryTotalViolations || 0
	theoryAbsences.value = data.theoryTotalAbsences || 0

	// 实践考试信息
	practiceViolations.value = data.practiceTotalViolations || 0
	practiceAbsences.value = data.practiceTotalAbsences || 0

	// 处理违规学生ID
	if (data.theoryViolationStudentIds) {
		const theoryViolationIds = data.theoryViolationStudentIds
			.split(',')
			.map((id: string) => parseInt(id.trim()))
		theoryViolationStudents.value = await Promise.all(
			theoryViolationIds.map((id: number) => fetchUserInfo(id))
		)
	} else {
		theoryViolationStudents.value = []
	}

	// 处理最高分学生ID
	if (data.topTheoryStudentIds) {
		const theoryTopIds = data.topTheoryStudentIds
			.split(',')
			.map((id: string) => parseInt(id.trim()))
		theoryTopStudents.value = await Promise.all(theoryTopIds.map((id: number) => fetchUserInfo(id)))
	} else {
		theoryTopStudents.value = []
	}

	// 处理实践违规学生ID
	if (data.practiceViolationStudentIds) {
		const practiceViolationIds = data.practiceViolationStudentIds
			.split(',')
			.map((id: string) => parseInt(id.trim()))
		practiceViolationStudents.value = await Promise.all(
			practiceViolationIds.map((id: number) => fetchUserInfo(id))
		)
	} else {
		practiceViolationStudents.value = []
	}

	// 处理实践最高分学生ID
	if (data.topPracticeStudentIds) {
		const practiceTopIds = data.topPracticeStudentIds
			.split(',')
			.map((id: string) => parseInt(id.trim()))
		practiceTopStudents.value = await Promise.all(
			practiceTopIds.map((id: number) => fetchUserInfo(id))
		)
	} else {
		practiceTopStudents.value = []
	}
}

// 使用成绩数据更新图表
const updateChartsFromScoreData = (data: TScore[]) => {
	// 根据选择的考试类型更新图表
	// console.log('Updating charts with data:', data.length)

	// 设置图表数据已初始化标志，无论是否有数据
	chartDataInitialized.value = true
	// console.log('Chart data initialized set to true')

	// 强制渲染图表，无需等待nextTick，函数内部会处理
	updateScoreDistribution(data)
	updateScorePercentage(data)
}

// 筛选数据
const filterScoreData = () => {
	// 获取统计数据
	fetchStatsData()
}

// 修改获取成绩数据的方法
const fetchScoreData = async () => {
	if (!userId) return Promise.resolve()
	try {
		const res = await getScoreListBySpecificService({ userId })
		processScoreData(res.data.data)

		// 如果有班级和学年数据，自动进行查询
		if (selectedYear.value && selectedClass.value) {
			nextTick(() => {
				// 先获取科目列表
				fetchSubjectsByClassAndYear().then(() => {
					// 有科目数据时，自动查询
					if (subjectList.value.length > 0) {
						handleQuery()
					}
				})
			})
		}

		return Promise.resolve()
	} catch (error) {
		// console.error('获取成绩数据失败:', error)
		ElMessage.error('获取基础数据失败，请刷新页面')
		return Promise.reject(error)
	}
}

// 离开页面时的处理
onDeactivated(() => {
	// 清理资源
})

// 当使用keep-alive组件时，页面重新激活时调用
onActivated(() => {
	// 总是重新获取班级和科目列表，确保下拉框有数据
	if (classList.value.length === 0 || subjectList.value.length === 0) {
		fetchScoreData()
	}

	// 从其他页面返回时的情况
	const fromUserInfo =
		route.query.fromUserInfo === 'true' || route.query.fromScoreDistribution === 'true'
	const hasRequiredParams = canQuery.value

	// 清除URL中的查询参数，防止刷新页面时重复查询
	if (fromUserInfo) {
		router.replace({ path: route.path, query: {} })
	}

	// 如果从用户信息页返回，执行查询
	if (fromUserInfo && hasRequiredParams) {
		nextTick(() => {
			handleQuery()
		})
	}
})

// 更新成绩分布图
const updateScoreDistribution = (data: TScore[]) => {
	console.log('updateScoreDistribution called, ref exists:', !!scoreDistributionRef.value)

	nextTick(() => {
		if (!scoreDistributionRef.value) {
			console.log('scoreDistributionRef is still null after nextTick')
			return
		}

		console.log('Initializing distribution chart after nextTick')
		// 如果图表实例已存在，则销毁它
		if (scoreDistributionChart) {
			scoreDistributionChart.dispose()
		}

		// 创建新的图表实例
		try {
			scoreDistributionChart = echarts.init(scoreDistributionRef.value)

			// 根据选择的考试类型获取不同的成绩数据
			const scores =
				data.length > 0
					? selectedScoreType.value === 'theory'
						? data.map((item) => item.theoryTotal)
						: data.map((item) => item.practiceTotal)
					: []

			const option: EChartsOption = {
				title: {
					text: selectedScoreType.value === 'theory' ? '理论考试成绩分布图' : '实践考试成绩分布图'
				},
				tooltip: {
					trigger: 'axis'
				},
				xAxis: {
					type: 'category',
					data: ['0-59', '60-69', '70-79', '80-89', '90-100']
				},
				yAxis: {
					type: 'value',
					name: '人数'
				},
				series: [
					{
						data: scores.length > 0 ? calculateScoreDistribution(scores) : [0, 0, 0, 0, 0],
						type: 'bar',
						name: '人数',
						itemStyle: {
							color: selectedScoreType.value === 'theory' ? '#409EFF' : '#67C23A'
						}
					}
				]
			}

			scoreDistributionChart.setOption(option)
			console.log('Distribution chart initialized successfully')
		} catch (error) {
			console.error('Error initializing distribution chart:', error)
		}
	})
}

// 更新成绩等级占比
const updateScorePercentage = (data: TScore[]) => {
	console.log('updateScorePercentage called, ref exists:', !!scorePercentageRef.value)

	nextTick(() => {
		if (!scorePercentageRef.value) {
			console.log('scorePercentageRef is still null after nextTick')
			return
		}

		console.log('Initializing percentage chart after nextTick')
		// 如果图表实例已存在，则销毁它
		if (scorePercentageChart) {
			scorePercentageChart.dispose()
		}

		// 创建新的图表实例
		try {
			scorePercentageChart = echarts.init(scorePercentageRef.value)

			// 如果没有数据，显示空图表
			if (data.length === 0) {
				const emptyOption: EChartsOption = {
					title: {
						text: selectedScoreType.value === 'theory' ? '理论考试等级占比' : '实践考试等级占比'
					},
					tooltip: {
						trigger: 'item'
					},
					series: [
						{
							type: 'pie',
							radius: ['40%', '70%'],
							data: [],
							emphasis: {
								itemStyle: {
									shadowBlur: 10,
									shadowOffsetX: 0,
									shadowColor: 'rgba(0, 0, 0, 0.5)'
								}
							}
						}
					]
				}
				scorePercentageChart.setOption(emptyOption)
				console.log('Empty percentage chart initialized')
				return
			}

			// 根据选择的考试类型获取不同的成绩数据
			const scores =
				selectedScoreType.value === 'theory'
					? data.map((item) => item.theoryTotal)
					: data.map((item) => item.practiceTotal)

			// 计算各等级人数
			const excellentCount = calculateGradeCount(scores, 80, 100)
			const passCount = calculateGradeCount(scores, 60, 79)
			const failCount = calculateGradeCount(scores, 0, 59)

			// 计算总人数
			const totalCount = scores.length

			// 计算各等级比例
			const excellentRate = totalCount > 0 ? (excellentCount / totalCount) * 100 : 0
			const passRate = totalCount > 0 ? (passCount / totalCount) * 100 : 0
			const failRate = totalCount > 0 ? (failCount / totalCount) * 100 : 0

			const option: EChartsOption = {
				title: {
					text: selectedScoreType.value === 'theory' ? '理论考试等级占比' : '实践考试等级占比'
				},
				tooltip: {
					trigger: 'item',
					formatter: '{b}率: {d}%'
				},
				series: [
					{
						type: 'pie',
						radius: ['40%', '70%'],
						data: [
							{ value: excellentRate, name: '优秀' },
							{ value: passRate, name: '及格' },
							{ value: failRate, name: '不及格' }
						],
						emphasis: {
							itemStyle: {
								shadowBlur: 10,
								shadowOffsetX: 0,
								shadowColor: 'rgba(0, 0, 0, 0.5)'
							}
						}
					}
				]
			}

			scorePercentageChart.setOption(option)
			console.log('Percentage chart initialized successfully')
		} catch (error) {
			console.error('Error initializing percentage chart:', error)
		}
	})
}

// 计算成绩分布
const calculateScoreDistribution = (scores: number[]) => {
	const distribution = [0, 0, 0, 0, 0]
	scores.forEach((score) => {
		if (score < 60) distribution[0]++
		else if (score < 70) distribution[1]++
		else if (score < 80) distribution[2]++
		else if (score < 90) distribution[3]++
		else distribution[4]++
	})
	return distribution
}

// 计算成绩等级占比
const calculateGradeCount = (scores: number[], min: number, max: number) => {
	return scores.filter((score) => score >= min && score <= max).length
}

const showStudentDetail = (studentId: number) => {
	// 跳转到用户详情页面，并传递参数标记是从成绩分布页面跳转过去的
	router.push({
		path: `/userInfo/${studentId}`,
		query: { fromScoreDistribution: 'true' }
	})
}

const handleQuery = () => {
	// 检查筛选条件是否完整
	if (!selectedYear.value || !selectedClass.value) {
		ElMessage.warning('请选择学年和班级')
		return
	}
	filterScoreData()
}

// 添加切换考试类型的处理函数
const handleScoreTypeChange = () => {
	// 如果已经有数据，则直接根据新的考试类型更新图表
	if (scoreData.value.length > 0) {
		updateChartsFromScoreData(scoreData.value)
		// 更新统计数据显示
		updateStatisticsDisplay()
	}
}

// 添加切换科目的处理函数
const handleSubjectChange = () => {
	// 如果有必要的查询条件，重新查询数据
	if (canQuery.value) {
		handleQuery()
	}
}

// 更新统计数据显示
const updateStatisticsDisplay = () => {
	if (allScoreData.value.length === 0) return

	try {
		// 基本查询参数
		const baseParams = {
			academicYear: selectedYear.value,
			classId: selectedClass.value
		}

		// 如果选择了科目，则添加到查询参数
		const params = selectedSubject.value
			? { ...baseParams, subjectId: selectedSubject.value }
			: baseParams

		// 查找匹配的统计数据
		getScoreStatsListService(params)
			.then((res) => {
				if (res.data.data && res.data.data.length > 0) {
					const data = res.data.data[0]

					// 根据所选考试类型更新统计数据
					if (selectedScoreType.value === 'theory') {
						statistics.value = [
							{ label: '平均分', value: data.avgScoreTheory?.toString() || '0' },
							{ label: '最高分', value: data.maxScoreTheory?.toString() || '0' },
							{ label: '最低分', value: data.minScoreTheory?.toString() || '0' },
							{ label: '及格率', value: `${data.passRateTheory || 0}%` }
						]
					} else {
						statistics.value = [
							{ label: '平均分', value: data.avgScorePractice?.toString() || '0' },
							{ label: '最高分', value: data.maxScorePractice?.toString() || '0' },
							{ label: '最低分', value: data.minScorePractice?.toString() || '0' },
							{ label: '及格率', value: `${data.passRatePractice || 0}%` }
						]
					}
				}
			})
			.catch((error) => {
				console.error('获取统计数据失败:', error)
			})
	} catch (error) {
		console.error('更新统计数据显示失败:', error)
	}
}
</script>

<style lang="scss" scoped>
.subject-analyze {
	max-height: 100%;
	padding: 20px;

	.analyze-card {
		.card-header {
			position: relative;
			display: flex;
			justify-content: space-between;
			align-items: center;

			.filter-section {
				display: flex;
				gap: 15px;
				flex-wrap: wrap;
				align-items: center;
				width: 100%;
				position: relative;

				.filter-item {
					width: 150px;
					// margin-bottom: 10px;
				}

				.query-btn {
					// margin-bottom: 10px;
				}

				.right-filters {
					position: absolute;
					right: 0;
					display: flex;
					justify-content: center;
					align-items: center;
				}
			}
		}
	}

	.charts-container {
		margin-top: 20px;
		min-height: 400px;
		position: relative;

		.empty-chart-tip {
			height: 400px;
			display: flex;
			justify-content: center;
			align-items: center;
			margin-bottom: 20px;

			.el-empty {
				padding: 40px 0;
			}
		}

		.chart-item {
			height: 400px;
			margin-bottom: 20px;
		}

		.statistics-row {
			margin: 20px 0;

			.stat-card {
				text-align: center;
				height: 100px;
				display: flex;
				flex-direction: column;
				justify-content: center;

				.stat-value {
					font-size: 24px;
					font-weight: bold;
					color: #409eff;
				}

				.stat-label {
					margin-top: 8px;
					color: #666;
				}
			}
		}

		.student-card {
			height: 100px;
			overflow-y: auto;

			.student-info {
				.student-label {
					font-weight: bold;
					margin-bottom: 8px;
					color: #666;
					text-align: center;
				}

				.student-list {
					display: flex;
					flex-wrap: wrap;
					gap: 5px;
					justify-content: center;

					.student-tag {
						cursor: pointer;
					}
				}
			}
		}
	}
}

// 响应式调整
@media screen and (max-width: 768px) {
	.subject-analyze {
		.analyze-card {
			.card-header {
				.filter-section {
					flex-direction: column;
					align-items: stretch;

					.filter-item {
						width: 100%;
					}

					.right-filters {
						position: static;
						margin-top: 10px;
						flex-direction: column;
						width: 100%;

						.filter-item {
							margin-right: 0 !important;
							margin-bottom: 10px;
							width: 100% !important;
						}
					}
				}
			}
		}

		.charts-container {
			.empty-chart-tip {
				height: 300px;
			}
		}
	}
}
</style>
